<script setup lang="ts">
import * as L from 'leaflet/dist/leaflet.js';
import 'leaflet/dist/leaflet.css';
import { message } from '@/utils/message';
import { nextTick, onBeforeMount, onMounted, onUnmounted, reactive, ref, shallowRef } from "vue";
import { colorType, iconType, useMarker } from "./marker";
import { MarkerOption, PopupOption } from "./types"

import SvgColors from "./svg-colors.vue"

import { isArray } from "@pureadmin/utils";
const props = defineProps({
  /** 背景图片 */
  bgImg: {
    type: String,
    // default: ""
    default: ""
  },
  /** 图标数组 */
  /*暂时不传  调用 setMarkers 设置*/
  /* markerArr: {
     type: Array<any>,
     default: []
   },*/
  /** 是否显示弹窗 */
  /*isShowPopup: {
    type: Boolean,
    default: false
  },*/
})

/**
 * markerAdd 添加标记点事件
 * markerClick 点击标记点事件
 * markerRemove 删除标记点事件
 * markerMouseover 鼠标移入标记点事件
 */
const emits = defineEmits(['init', 'markerClick', 'markerMouseover'])

const { getSvgIcon } = useMarker()

// const popupContentRef = ref()
// const fixedPoints = shallowRef([])  // onMounted初始化图标实例

const mapState = reactive({
  showPop: false,
  width: 0,
  height: 0,
  loading: false,
  loadImgErr: false,
  errMsg: "",
  timer: null
})

const containerRef = ref()
//map对象 不能使用 ref
let map = null, imageOverlay = null, markers = []
const container = ref("")

onBeforeMount(() => {
  container.value = "container" + Math.ceil(Math.random() * 100)
})

onMounted(() => {
  // init(props.bgImg)
})

onUnmounted(() => {
  if (map) {
    map.remove()
  }
})

async function init(img) {
  if (map) {
    map.remove()
  }
  mapState.loading = true
  mapState.loadImgErr = false
  getImageInfo(img).then(res => {
    mapState.width = res.width
    mapState.height = res.height
    nextTick(() => {
      initMap().then(res => {
        setImageLayer(img)
      })
    })
  }).catch(err => {
    mapState.loadImgErr = true
    mapState.errMsg = img ? '图片加载失败' : '暂无图纸信息'
    message('图纸加载失败', { type: 'error' })
  }).finally(() => {
    mapState.loading = false
  })
}

//初始化地图
const initMap = async () => {
  map = L.map(container.value, {
    maxZoom: 20,
    zoom: 0,
    minZoom: -1,
    zoomDelta: 1,
    zoomControl: false,
    attributionControl: false,
    doubleClickZoom: false,
    wheelPxPerZoomLevel: 200,
    zoomSnap: 0,
    crs: L.CRS.Simple
  })//.setView([51.505, -0.09], 3);

 
  emits('init', map)
  // map.on('resize', setImageLayer);
}

//设置地图图片图层
const setImageLayer = async (img) => {

  // 移除现有的覆盖层（如果有）
  if (imageOverlay) {
    map.removeLayer(imageOverlay);
  }
  // const bounds = getBounds();
  const bounds = [[0, 0], [mapState.height, mapState.width]]
  imageOverlay = L.imageOverlay(img, bounds, {
    interactive: true,
    noClip: true
  }).addTo(map)
  map.fitBounds(bounds);
}

/*
* iconStr svg图标
* */
const addMarker = (lat: string, lng: string, iconStr: string, iconType: iconType = "building", color: colorType = 'blue', markerItem = {}, popupOption: PopupOption) => {
  
  const sol = L.latLng(lat, lng); // x,y 相反
  // / 创建一个SVG图标
  var svgIcon = getSvgIcon(iconStr, iconType, color, popupOption)

  // 将SVG字符串转换为图像标签
  var icon = L.divIcon({
    html: svgIcon.svg,
    className: 'svg-marker',
    ...svgIcon.options
  });
  const marker = L.marker(sol, {
    draggable: false,
    autoPan: true,
    riseOnHover: true,
    icon: icon,
  });
  Object.assign(marker.options, { markerItem: markerItem })
  marker.on('click', (e) => {
    // console.log(e,"点击事件")
    emits('markerClick', parseMarker(marker))
  })
  // marker.on('mouseover', (e) => {
  //   emits('markerMouseover', e)
  // })
  console.log("map:", marker);

  marker.addTo(map)

  if (popupOption?.showPopup) {

    // marker.bindPopup(usePopup().createBuildingPopupContent(color, popupOption), {
    //   closeButton: false,
    //   autoClose: false,
    //   closeOnClick: false,
    //   // offset:[0,-63]
    //   offset: [4.35, 14]
    // }).openPopup();
    // marker.on('click', function () {
    //   console.log('跳转到详情页面的方法');
    // })
  
    // L.popup({
    //   closeButton: false,
    //   autoClose: false,
    //   closeOnClick:false,
    //   // offset:[0,-63]
    //   offset:[4.35,14]
    // }).setLatLng(marker.getLatLng())
    //   .setContent(usePopup().createBuildingPopupContent(color, popupOption))
    //   .openOn(map);
  }
  markers.push(marker)

  return marker
}


const parseMarker = (markerArr: any[] | any) => {
  if (isArray(markerArr)) {
    let res = []
    markerArr.forEach((item) => {
      res.push({
        lat: item.getLatLng().lat,
        lng: item.getLatLng().lng,
        iconUrl: item.getIcon().options.icon,
      })
    })
    return res
  } else {
    return [{
      lat: markerArr.getLatLng().lat,
      lng: markerArr.getLatLng().lng,
      iconUrl: markerArr.getIcon().options.icon,
      markerItem: markerArr.options.markerItem
    }]
  }
}

//显示pop弹窗
/*const showMarkerPop = (marker) => {
  mapState.showPop = true
  nextTick(() => {
    marker.bindPopup(popupContentRef.value, {
      closeOnClick: false,
      closeButton: false,
      offset: [1, -6]
    }) // 绑定pop弹出层
      .openPopup(); // 打开pop弹出层
  })
}*/

//切换图片
const changeImgLayer = async (imageUrl) => {
  clearMarkers().then(async res => {
    
    if (map) {
      getImageInfo(imageUrl).then(res => {
        mapState.width = res.width
        mapState.height = res.height
        nextTick(() => {
          setImageLayer(imageUrl)
        })
      }).catch(err => {
        mapState.loadImgErr = true
        mapState.errMsg = imageUrl ? '图片加载失败' : '暂无图纸信息'
        message('图纸加载失败', { type: 'error' })
      }).finally(() => {
        mapState.loading = false
      })
    } else {
      await init(imageUrl)
    }
  })
 
  // imageOverlay.setUrl(imageUrl)
  // init(imageUrl)

}

const getImageInfo = async (img: HTMLImageElement | string): Promise<{ width: number, height: number }> => {
  return new Promise((resolve, reject) => {
    let resImg = null
    if (typeof img === 'string') {
      resImg = new Image()
      resImg.src = img
    } else {
      resImg = img
    }
    resImg.onload = () => {
      resolve({
        width: resImg.width,
        height: resImg.height
      })
    }
    resImg.onerror = () => {
      reject(new Error('图纸加载失败'))
    }
  })
}

/*自定义设置icon*/
const setMarkers = async (markers: MarkerOption[]) => {
  console.log(markers,"收到22")

  clearMarkers().then(() => {
    if(!map) {
      if (!mapState.timer) {}
        mapState.timer = setInterval(() => {
          if(map) {
            clearInterval(mapState.timer)
            mapState.timer = null
            markers.forEach(marker => {
              addMarker(marker.lat, marker.lng, marker.iconSvg, marker.iconType, marker.color, marker.markerItem, marker.popupOption)
            })
          }
        }, 800);
    }else{
      markers.forEach(marker => {
          addMarker(marker.lat, marker.lng, marker.iconSvg, marker.iconType, marker.color, marker.markerItem, marker.popupOption)
        })
    }
    
  })

}
const clearMarkers = async () => {
   
  if (map && markers.length > 0) {
    markers.forEach((marker) => {
      marker.remove()
    })
    markers = []
  }
}

defineExpose({
  changeImgLayer,
  setMarkers,
  clearMarkers
})
</script>

<template>
  <div class="w-full h-full show-map-maker" v-loading="mapState.loading">
    <div :id="container" ref="containerRef" class="size-full !bg-[#0b1019]" v-if="!mapState.loadImgErr"></div>
    <template v-else>
      <el-empty class="h-full" image-size="200" :description="mapState.errMsg"></el-empty>
    </template>
    <!--    <div ref="popupContentRef" v-show="isShowPopup && mapState.showPop">
      <slot>

      </slot>
    </div>-->
    <svg-colors />
  </div>
</template>

<style lang="scss">
.show-map-maker {
  .leaflet-pane {
    z-index: 0;
  }

  .el-loading-mask {
    z-index: 0;
  }

  .leaflet-popup-content-wrapper,
  .leaflet-popup-tip {
    background-color: transparent !important;
    box-shadow: none !important;
  }
}
</style>
